import Vue from 'vue'
import ComToast from '../components/com-toast.vue'

const ToastConstructor = Vue.extend(ComToast)

const toast = (params) => {
    let options = {}
    try {
        if (Object.prototype.toString.call(params) === '[object String]') {
            options.content = params
        } else if (Object.prototype.toString.call(params) === '[object Object]') {
            options = params
        } else {
            throw new Error('params must be string or object')
        }
    } catch (err) {
        console.error(err)
        return
    }
    const {
        autoCloseTime,
        ...props
    } = options
    const instance = new ToastConstructor({
        propsData: {
            ...props
        },
        data: {
            autoCloseTime: autoCloseTime === undefined ? 3000 : autoCloseTime
        }
    })
    instance.vm = instance.$mount()
    instance.vm.visible = true
    document.body.appendChild(instance.vm.$el)
    instance.vm.$on('close', () => {
        document.body.removeChild(instance.vm.$el)
        instance.vm.$destroy()
    })
}

export default toast
